﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using iOSClub.App.Desktop.Pages;
using iOSClub.App.Share.WeatherModels;

namespace iOSClub.App.Desktop.ViewModels.Pages;

public class WeatherPageModel : PageModelBase
{
    public override Control Init()
    {
        IsLoad = false;
        return new WeatherPage() { DataContext = this };
    }
    
    private bool _isLoad;

    public bool IsLoad
    {
        get => _isLoad;
        set => SetProperty(ref _isLoad, value);
    }

    private DateTime _now;

    public DateTime Now
    {
        get => _now;
        set => SetProperty(ref _now, value);
    }

    private WeatherList _list = new();

    public WeatherList List
    {
        get => _list;
        set => SetProperty(ref _list, value);
    }

    public async Task Change(string? locString)
    {
        var loc = Weather.DefaultCity;
        if (!string.IsNullOrEmpty(locString))
        {
            var locations = await Weather.GetLoc(locString);
            var l = locations.FirstOrDefault();
            if (l != null) loc = l;
        }

        List = await Weather.GetData(loc);
        Now = DateTime.Now;
        IsLoad = true;
    }

    public async Task Refresh()
    {
        IsLoad = false;
        var now = DateTime.Now;
        if ((now - _now).TotalMinutes < 30) return;
        var locations = await Weather.GetLoc(List.CityName);
        var l = locations.FirstOrDefault();
        if (l != null) List = await Weather.GetData(l);
        Now = DateTime.Now;
        IsLoad = true;
    }
}